package cn.sail.shop3.api.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Properties;

public class DBUtil {

    private static ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();

    public static void transactionStart() {
        //获取连接对象
        //设置关闭自动提交，开启事务
        try {
            connectionThreadLocal.get().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void transactionCommit() {
        //获取连接对象
        //提交事务
        try {
            connectionThreadLocal.get().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void transactionRollback() {
        //获取连接对象
        //回滚事务
        try {
            connectionThreadLocal.get().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接对象
     *
     * @return
     */
    public static Connection getConnectionLocal() {
        if (null != connectionThreadLocal.get()) {
            return connectionThreadLocal.get();
        }

        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //连接数据库
            String url = "jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
            String jdbcUserName = "root";
            String password = "root";
            Connection connection = DriverManager.getConnection(url, jdbcUserName, password);
            connectionThreadLocal.set(connection);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connectionThreadLocal.get();
    }

    public static Connection getConnection() {
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //连接数据库
            String url = "jdbc:mysql://localhost/shop?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
            String jdbcUserName = "root";
            String password = "root";
            Connection connection = DriverManager.getConnection(url, jdbcUserName, password);
            return connection;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放资源
     *
     * @param resultSet
     * @param statement
     * @param connection
     */
    public static void closeAll(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (null != resultSet) {
                resultSet.close();
            }
            statement.close();
            if (null != connection) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        }
    }

    public static void closeConnection() {
        Connection connectionLocal = getConnectionLocal();
        try {
            connectionLocal.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static <T> T convertResultSetToEntity(ResultSet resultSet, Class<T> entityClass) {
        try {
            //根据类型创建类型对象
            T entityObj = entityClass.newInstance();
            //resultSet 结果填充到 类型对象中
            //获取类型的所有的属性
            String columnName;
            Class<?> fieldType;
            while (resultSet.next()) {
                for (Field field : entityClass.getDeclaredFields()) {
                    field.setAccessible(true);
                    //根据属性名获取字段名 驼峰命名转换_分割
                    columnName = StringUtils.humpToUnderline(field.getName());
                    //根据属性类型获取字段值得类型
                    fieldType = field.getType();
                    //从resultSet获取字段值
                    if (fieldType.equals(String.class)) {
                        //字段值填充到对象中
                        field.set(entityObj, resultSet.getString(columnName));
                    }
                    if (fieldType.equals(Long.class)) {
                        //字段值填充到对象中
                        field.set(entityObj, resultSet.getLong(columnName));
                    }
                    if (fieldType.equals(BigDecimal.class)) {
                        //字段值填充到对象中
                        field.set(entityObj, resultSet.getBigDecimal(columnName));
                    }
                }
            }
            //返回对象结果
            return entityObj;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static DataSource dataSource;

    public static DataSource getDataSource() {
        if (null != dataSource) {
            return dataSource;
        }
        try {
            Properties properties = new Properties();
            InputStream resourceAsStream = DBUtil.class.getClassLoader()
                    .getResourceAsStream("db.properties");
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
            return dataSource;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
